//
//  RHShareVideoListVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/7/12.
//

#import "RHShareVideoListVC.h"
#import "RHVideoAuditCell.h"
#import "SJVideoModel.h"
#import "SJVideoCellViewModel.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import "RHVideoModel.h"

@interface RHShareVideoListVC ()<UITableViewDelegate,UITableViewDataSource,VideoCellDelegate,QMUITextFieldDelegate>

@property (nonatomic, strong, nullable) SJVideoPlayer *player;

@property (nonatomic, strong) NSMutableArray<RHVideoModel *> *models;

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic ,copy) NSString *keyCode;

@end

@implementation RHShareVideoListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _videoListArr = [NSMutableArray array];
    self.view.backgroundColor = CFTabViewBgColor;
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.numOfPage = 20;
    [self setupUI];
    [self getVideoData];
}

- (void)setupUI{
    //配置
    SJVideoPlayer.updateResources(^(id<SJVideoPlayerControlLayerResources>  _Nonnull resources) {
        resources.placeholder = [UIImage imageNamed:@"placeholder"];
        resources.progressThumbSize = 8;
        resources.progressTrackColor = [UIColor colorWithWhite:0.8 alpha:1];
        resources.progressBufferColor = [UIColor whiteColor];
        resources.progressThumbImage = [UIImage imageNamed:@"thumb"];
        
    });
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView registerClass:[RHVideoAuditCell class] forCellReuseIdentifier:@"RHVideoAuditCell"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        weakSelf.keyCode = @"";
        [weakSelf getVideoData];
//        if(weakSelf.refreshBlock){
//            weakSelf.refreshBlock();
//        }
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getVideoData];
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 13.0, *)) {
        _tableView.automaticallyAdjustsScrollIndicatorInsets = NO;
        
    }
    
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
}

-(void)searchDeviceWithKeyCode:(NSString*)keyCode
{
    self.currentPage = 1;
    self.requestType = RequestTypeRefresh;
    [self.tableView endFooterResetNoMoreData];
    self.keyCode = keyCode;
    [self getVideoData];
}


#pragma mark -------- 视频分享列表
-(void)getVideoData
{
    //0待审核 1 已分享（审核通过）2 驳回
    NSInteger checkIndex = 0;
    if (self.index == 1) {
        checkIndex = 1;
    }else if(self.index == 2){
        checkIndex = 0;
    }else if(self.index == 3){
        checkIndex = 2;
    }
    [QMUITips showLoadingInView:self.view];
    NSMutableDictionary *para = @{
                           @"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"title":ValidNullData(self.keyCode),
                           @"checkStatus":@(checkIndex),
                           @"userId":@([PrivateMange share].currentUser.userId)
    }.mutableCopy;
    if (self.index == 0) {
        [para removeObjectForKey:@"checkStatus"];
    }
    [RHVideoModel startGetWithCompletionAPIKey:H_getCaseStudyVideo argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if (resultModel.code == 200) {
            NSArray *arr = resultModel.data;
            
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            
          
//            NSMutableArray *mtbArr = [NSMutableArray array];
//            for ( SJVideoModel *item in arr ) {
//                [mtbArr addObject:[SJVideoCellViewModel.alloc initWithItem:item]];
//            }
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                [self.tableView endHeaderRefresh];
                self.models = arr.mutableCopy;
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.models addObjectsFromArray:arr];
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshCustomWithNoMoreData];
            }
         
           
            if(arr.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
            
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

- (void)coverItemWasTapped:(RHVideoAuditCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    RHVideoModel *vm = _models[indexPath.row];
    
    if ( !_player ) {
        _player = [SJVideoPlayer player];
        
    }
    
    _player.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:[NSURL URLWithString:vm.videoLink] playModel:[SJPlayModel playModelWithTableView:_tableView indexPath:indexPath superviewSelector:NSSelectorFromString(@"videoCoverView")]];
    _player.URLAsset.title = vm.title;

  
    _player.rotationObserver.onRotatingChanged = ^(id<SJRotationManager>  _Nonnull mgr, BOOL isRotating) {
        if(isRotating  ){
            if(mgr.currentOrientation == 3){
                [AppDelegate shareAppDelegate].allowRotate = YES;
            }else{
                [AppDelegate shareAppDelegate].allowRotate = NO;
            }
            
        }
    
    };
}


#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  _models.count;
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//    return [_models[indexPath.row] height] + 40;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RHVideoAuditCell *videoCell = [tableView dequeueReusableCellWithIdentifier:@"RHVideoAuditCell"];
    videoCell.videoModel = _models[indexPath.row];
    kWeakSelf;
    videoCell.deleteAction = ^(RHVideoModel * videoModel) {
        QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:@"删除此视频?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
        QMUIAlertAction *cancel = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:nil];
        QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
            [weakSelf deleteVideo:videoModel];
        }];
        [alertVC addAction:cancel];
        [alertVC addAction:sure];
        [alertVC showWithAnimated:YES];
        
    };
    return videoCell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(RHVideoAuditCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    cell.delegate = self;
}

#pragma mark ----- 删除视频
-(void)deleteVideo:(RHVideoModel*)videoModel
{
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_deleteCaseStudyVideo,videoModel.videoId];
    [BaseModel startDeleteWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"删除成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self getVideoData];
                [[NSNotificationCenter defaultCenter]postNotificationName:VIDEO_DELETE_NOTIFICATION object:nil];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.player vc_viewDidAppear];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.player vc_viewWillDisappear];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.player vc_viewDidDisappear];
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (BOOL)prefersHomeIndicatorAutoHidden {
    return YES;
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}



@end
